package top.ajun.mall.product.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.ajun.common.exception.CodeEnum;
import top.ajun.common.utils.R;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一异常处理
 *
 * @author AJun
 * @date 2020/12/1
 */
@Slf4j
@RestControllerAdvice("top.ajun.mall.product.controller")
public class MallExceptionControllerAdvice {

    @ExceptionHandler(Throwable.class)
    public R handleException(Throwable throwable) {
        log.error("系统出现异常{}, 异常类型{}", throwable.getMessage(), throwable.getClass());
        return R.error(CodeEnum.UNKNOWN_EXCEPTION.getCode(), CodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现异常{}, 异常类型{}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        result.getFieldErrors().forEach(item -> {
            // 错误提示
            String errorMsg = item.getDefaultMessage();
            // 发生错误的属性名称
            String field = item.getField();
            errorMap.put(field, errorMsg);
        });
        return R.error(CodeEnum.VALID_EXCEPTION.getCode(), CodeEnum.VALID_EXCEPTION.getMsg()).put("data", errorMap);
    }

}
